import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/country_entity.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';

import 'default_bottom_sheet.dart';

/// 选择城市
///
/// 返回城市
showCountryBottomSheet(
    BuildContext context, CountryEntity currentSelect) async {
  CountryEntity _currentSelect = currentSelect;

  await showDefaultBottomSheet(
    context,
    bottomMargin: 0,
    child: CountryWidget(
      currentSelect: currentSelect,
      selectCallBack: (data) {
        _currentSelect = data;
      },
    ),
    title: S.current.country,
    isScrollControlled: true,
  );
  return _currentSelect;
}

class CountryWidget extends StatefulWidget {
  final CountryEntity currentSelect;
  final ValueChanged<CountryEntity> selectCallBack;

  CountryWidget({Key key, this.currentSelect, this.selectCallBack})
      : super(key: key);

  @override
  _CountryWidgetState createState() => _CountryWidgetState();
}

class _CountryWidgetState extends State<CountryWidget> {
  TextEditingController _searchController = TextEditingController();
  FocusNode _searchFocusNode = FocusNode();
  Map<String, List<CountryEntity>> data = {};
  CountryEntity _currentSelect;

  @override
  void initState() {
    super.initState();
    Map<String, List<CountryEntity>> _data = {};
    final copyList = List<CountryEntity>.of(Config.settingData.country ?? []);
    copyList.sort((a, b) => a.key.compareTo(b.key));
    for (final item in copyList) {
      if (_data.containsKey(item?.key[0].toUpperCase())) {
        List groupMap = _data[item.key[0].toUpperCase()];
        groupMap.add(item);
      } else {
        _data[item.key[0].toUpperCase()] = [item];
      }
    }
    data = _data;
    _currentSelect = widget.currentSelect;
    _searchController.addListener(_handleSearchInput);
  }

  void _handleSearchInput() {
    setState(() {});
  }

  bool _onSearchInputGroup(MapEntry<String, List<CountryEntity>> element) {
    String searchInput = _searchController.text;
    List<CountryEntity> result = [];
    for (final item in element.value) {
      if (RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.name) ||
          RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.key)) {
        result.add(item);
      }
    }
    return result.length > 0;
  }

  List<CountryEntity> _onSearchInputItem(List<CountryEntity> element) {
    String searchInput = _searchController.text;

    List<CountryEntity> data = [];
    for (final item in element) {
      if (RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.name) ||
          RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.key)) {
        data.add(item);
      }
    }
    return data;
  }

  @override
  void dispose() {
    super.dispose();
    _searchController.dispose();
    _searchFocusNode.dispose();
  }

  void onChangeSelectCode(CountryEntity value) {
    if (value != _currentSelect) {
      setState(() {
        _currentSelect = value;
      });
      widget.selectCallBack?.call(_currentSelect);
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height * 0.30;
    List<Widget> slivers;
    if (_searchController.text.isNotEmpty) {
      slivers = data.entries
          .toList()
          .where(_onSearchInputGroup)
          .map((e) => buildSliver(e.key, _onSearchInputItem(e.value)))
          .toList();
    } else {
      slivers = data.entries
          .toList()
          .map((e) => buildSliver(e.key, e.value))
          .toList();
    }
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        AppSpaces.h10,
        SearchInputField(
          key: ValueKey('Search Input'),
          controller: _searchController,
          focusNode: _searchFocusNode,
        ),
        SizedBox(
          height: getDp(17),
        ),
        SizedBox(
          height: height,
          child: CupertinoScrollbar(
            child: CustomScrollView(
              slivers: slivers,
            ),
          ),
        ),
      ],
    );
  }

  Widget buildSliver(String title, List<CountryEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<CountryEntity> data, int i) {
    bool isSelect = _currentSelect == data[i];
    return PressedOpacityButton(
      onPressed: () => onChangeSelectCode(data[i]),
      padding: EdgeInsets.symmetric(
        horizontal: getDp(30),
        vertical: getDp(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          NormalRadio(
            isSelect: isSelect,
            title: data.toList()[i].name,
          ),
        ],
      ),
    );
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
